/**
 * 
 */
package com.mzba.place.ui;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.mzba.place.BaseFragmentActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.PusherService;
import com.mzba.place.R;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportInfoGson;
import com.mzba.place.fragment.CautionsFragment;
import com.mzba.place.fragment.MapFragment;
import com.mzba.place.fragment.MyNotificationFragment;
import com.mzba.place.fragment.ReportListFragment;
import com.mzba.place.fragment.SlidingSettingFragment;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
import com.slidingmenu.lib.SlidingMenu;

/**
 * @author Iris
 * 
 */
public class MainActivity extends BaseFragmentActivity implements Callback {

	private FragmentTransaction fragmentTransaction;

	public Menu menu;
	public MapFragment mapFragment;
	public ReportListFragment listFragment;

	private final int menu_search = 1;
	private final int menu_add = 2;
	private final int menu_filter = 3;
	private final int menu_my_position = 4;
	private final int menu_confirm = 5;
	private final int menu_share = 6;
	private final int menu_notification = 7;
	
	private final int menu_notification_read = 8;
	private final int search_address_requescode = 5;
	public final int setting_caustions_requestcode = 6;

	public final int upload_report_requestcode = 7;

	private List<ReportEntity> reports;
	public Fragment currentFragment = new Fragment();
	private SlidingSettingFragment slidingFragment;

	private SlidingMenu sm;

	public int report_type;
	public int report_time;

	private final int filter_reports = 1;
	private Handler handler;
	public boolean isLoading;

	public boolean firstReportType;
	public boolean firstReportTime;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler(this);
		setContentView(R.layout.activity_frame_content);
		setBehindContentView(R.layout.fragment_menu_frame);
		fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
		slidingFragment = new SlidingSettingFragment();
		fragmentTransaction.replace(R.id.menu_frame, slidingFragment);
		fragmentTransaction.commit();
		initSlidingMenu();
		setSupportProgressBarIndeterminateVisibility(false);
		actionBar.show();
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayUseLogoEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setLogo(R.drawable.hamburger);

		initHome();
		UICore.getInstance();
		Intent service = new Intent(this, PusherService.class);
		startService(service);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (slidingFragment != null) {
			slidingFragment.refreshUserInfo();
		}
		load();
	}

	public void initHome() {
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		Tab tab = actionBar.newTab().setText("地图").setTabListener(new TabListener<MapFragment>(this, "地图", MapFragment.class));
		actionBar.addTab(tab);

		Tab tab2 = actionBar.newTab().setText("列表").setTabListener(new TabListener<ReportListFragment>(this, "列表", ReportListFragment.class));
		actionBar.addTab(tab2);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.menu = menu;
		Log.d("debug", "--menu");
		setMapMenu();
		return true;
	}

	/**
	 * 初始化Sliding Menu
	 */
	private void initSlidingMenu() {
		// customize the SlidingMenu
		sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setBehindOffset(CanvasWidth / 3);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			break;
		case menu_my_position:
			if (mapFragment != null) {
				mapFragment.menuMyPosition();
			}
			break;
		case menu_add:
			Intent intent1 = new Intent(this, ReportUploadActivity.class);
			startActivityForResult(intent1,upload_report_requestcode);
			break;
		case menu_filter:
			if (mapFragment != null) {
				if (mapFragment.filterView.getVisibility() == View.VISIBLE) {
					mapFragment.filterView.setVisibility(View.GONE);
				} else {
					mapFragment.filterView.setVisibility(View.VISIBLE);;
				}
			}
			if (listFragment != null) {
				if (listFragment.filterView.getVisibility() == View.VISIBLE) {
					listFragment.filterView.setVisibility(View.GONE);
				} else {
					listFragment.filterView.setVisibility(View.VISIBLE);;
				}
			}
			break;
		case menu_search:
			Intent intent2 = new Intent(this, SearchAddressActivity.class);
			startActivityForResult(intent2, search_address_requescode);
			break;
		case menu_notification:
			Intent intent3 = new Intent(this, MyAllNotificationActivity.class);
			startActivity(intent3);
			break;
		case menu_notification_read:
			MyNotificationFragment myNotificationFragment =(MyNotificationFragment)currentFragment;
			myNotificationFragment.setAllNotificationRead();
			break;
		case menu_confirm:
			Intent intent4 = new Intent(this, SettingCaustionsActivity.class);
			startActivityForResult(intent4, setting_caustions_requestcode);
		default:
			break;
		}
		return false;
	}
	
	public void load() {
		UICore.eventTask(this, this, filter_reports, null, true);
	}

	public void setMapMenu() {
		actionBar.setTitle(R.string.fragment_map);
		Log.d("debug", "map--menu");
		setSupportProgressBarIndeterminateVisibility(false);
		if (menu != null && mapFragment != null) {
			menu.clear();
			menu.add(Menu.NONE, menu_add, Menu.NONE, "上报标记")
					.setIcon(R.drawable.icon_add).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			SubMenu subMenu = menu.addSubMenu("更多");
			subMenu.add(0, menu_search, 0, getString(R.string.menu_search))
					.setIcon(R.drawable.icon_search)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			subMenu.add(Menu.NONE, menu_filter, Menu.NONE,
					getString(R.string.menu_filter)).setIcon(R.drawable.icon_filter);
			subMenu.add(Menu.NONE, menu_my_position, Menu.NONE,
					getString(R.string.menu_location)).setIcon(
					R.drawable.icon_myposition);

			MenuItem subMenuItem = subMenu.getItem();
			subMenuItem
					.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
			subMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
					| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
	}

	public void setListMenu() {
		setSupportProgressBarIndeterminateVisibility(false);
		if (menu != null && listFragment != null) {
			menu.clear();
			menu.add(0, menu_add, 0, "上报标记").setIcon(R.drawable.icon_add)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menu.add(0, menu_filter, 0, "数据筛选").setIcon(R.drawable.icon_filter)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
	}

	public void setSettingMenu() {
		actionBar.setTitle(R.string.fragment_setting);
		setSupportProgressBarIndeterminateVisibility(false);
		if (menu != null) {
			menu.clear();
			menu.add(0, menu_confirm, 0, "设置").setIcon(R.drawable.ic_menu_setting).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
	}
	
	public void setSafecardMenu() {
		actionBar.setTitle(R.string.fragment_safecard);
		setSupportProgressBarIndeterminateVisibility(false);
		if (menu != null) {
			menu.clear();
			menu.add(0, menu_confirm, 0, "设置").setIcon(R.drawable.ic_menu_setting).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menu.add(0, menu_share, 0, "分享").setIcon(R.drawable.icon_share).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
	}

	/**
	 * 通知
	 */
	public void setAllNotificationMenu() {
		setSupportProgressBarIndeterminateVisibility(false);
		if (menu != null) {
			menu.clear();
			menu.add(0, menu_notification, 0, "所有的通知").setIcon(R.drawable.ic_notification_all).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menu.add(0, menu_notification_read, 0, "所有的通知为已读").setIcon(R.drawable.ic_notification_all_read).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if (UICore.getInstance().getPusherService() != null) {
			UICore.getInstance().setMainActivityExist(true);
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		if (mapFragment != null && mapFragment.mMapView != null) {
			mapFragment.mMapView.onPause();
		}
		if (UICore.getInstance().getPusherService() != null) {
			UICore.getInstance().setMainActivityExist(true);
		}
	}

	@Override
	public void onDestroy() {
		if (UICore.getInstance().getPusherService() != null) {
			UICore.getInstance().setMainActivityExist(false);
		}
		if (mapFragment != null) {
			if (mapFragment.mMapView != null) {
				mapFragment.mMapView.destroy();
			}
			if (mapFragment != null) {
				mapFragment.mLocClient.stop();
				mapFragment.mLocClient = null;
			}
			PlaceApplication app = (PlaceApplication) getApplication();
			if (app.mBMapManager != null) {
				app.mBMapManager.destroy();
				app.mBMapManager = null;
			}
		}
		super.onDestroy();
	}

	public void setReports(List<ReportEntity> reports) {
		this.reports = reports;
	}

	public List<ReportEntity> getReports() {
		return reports;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == search_address_requescode) {
				if (data != null) {
					int latitude = data.getIntExtra("latitude", 0);
					int longitude = data.getIntExtra("longitude", 0);
					mapFragment.setLatitude(latitude);
					mapFragment.setLongitude(longitude);
					mapFragment.searchAddress();
				}
			} else if (requestCode == setting_caustions_requestcode) {
				if (currentFragment instanceof CautionsFragment) {
					CautionsFragment settingFragment = (CautionsFragment) currentFragment;
					settingFragment.load();
				}
			}else if (requestCode ==upload_report_requestcode) {
				mapFragment.load();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (sm.isMenuShowing()) {
				toggle();
			} else {
				if (currentFragment instanceof SherlockFragment) {
					currentFragment = new Fragment();
		        	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
				} else {
					showExitMess("确定要退出治安雷达吗？");
				}
			}
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			moveTaskToBack(true);
		}
		return true;
	}

	/**
	 * 退出系统提示
	 * 
	 * @param mes
	 */
	public void showExitMess(String mes) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (!alertIsShow) {
			new AlertDialog.Builder(this)
					.setTitle("系统信息")
					.setMessage(mes)
					.setPositiveButton("是",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.dismiss();
									android.os.Process.killProcess(android.os.Process.myPid());
									System.exit(0);
								}
							})
					.setNegativeButton("否",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).show();
		}
	}

	public class TabListener<T extends SherlockFragment> implements
			ActionBar.TabListener {
		private Fragment mFragment;
		private final Activity mActivity;
		private final String mTag;
		private final Class<T> mClass;

		public TabListener(Activity activity, String tag, Class<T> clz) {
			mActivity = activity;
			mTag = tag;
			mClass = clz;
		}

		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			FragmentTransaction ftt = getSupportFragmentManager()
					.beginTransaction();
			if (mFragment == null) {
				mFragment = Fragment.instantiate(mActivity, mClass.getName());
				if (ftt != null) {
					ftt.add(android.R.id.content, mFragment, mTag);
				}
				if (mClass.getName().equals(MapFragment.class.getName())) {
					mapFragment = (MapFragment) mFragment;
					mapFragment.initFilterView();
					setMapMenu();
				} else if (mClass.getName().equals(ReportListFragment.class.getName())) {
					listFragment = (ReportListFragment) mFragment;
					listFragment.initFilterView();
					setListMenu();
				}
			} else {
				if (ftt != null) {
					ftt.show(mFragment);
					if (mClass.getName().equals(MapFragment.class.getName())) {
						mapFragment = (MapFragment) mFragment;
						mapFragment.initFilterView();
						setMapMenu();
					} else if (mClass.getName().equals(ReportListFragment.class.getName())) {
						listFragment = (ReportListFragment) mFragment;
						listFragment.initFilterView();
						setListMenu();
					}
				}
			}
			ftt.commit();

		}

		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			FragmentTransaction ftt = getSupportFragmentManager()
					.beginTransaction();
			if (mFragment != null) {
				if (ftt != null) {
					ftt.hide(mFragment);
				}
			}
			ftt.commit();
		}

		public void onTabReselected(Tab tab, FragmentTransaction ft) {

		}
	}
	
	/**
	 * 筛选reports
	 * 
	 * @param type 1: 扒窃抢劫 2: 色狼变态 3: 走失拐卖 4: 苹果丢了
	 * @param time 上报信息时间范围，1: 最近3天 2: 最近一周 3: 最近一个月 4: 最近半 年 5: 最近一年
	 */
	public void filterReports() {
		try {
			GeoPoint leftPoint = Utils.getLeftTopPoint(mapFragment.mMapView);
			GeoPoint rightPoint = Utils.getRightBottmPoint(mapFragment.mMapView);
			StringBuilder builder = new StringBuilder();
			builder.append(UrlConfig.reports);
			builder.append("?auth_token=");
			builder.append(AppContext.getInstance().getAuthToken());
			builder.append("&min_y=");
			builder.append(String.valueOf(leftPoint.getLatitudeE6() / 1E6));
			builder.append("&min_x=");
			builder.append(String.valueOf(leftPoint.getLongitudeE6() / 1E6));
			builder.append("&max_y=");
			builder.append(String.valueOf(rightPoint.getLatitudeE6() / 1E6));
			builder.append("&max_x=");
			builder.append(String.valueOf(rightPoint.getLongitudeE6() / 1E6));
			if (report_type != 0) {
				builder.append("&r_type=");
				builder.append(String.valueOf(report_type));
			}
			if (report_time != 0) {
				builder.append("&r_time=");
				builder.append(String.valueOf(report_time));
			}
			builder.append("&from=android_app");
			String response = HttpUtils.doGet(builder.toString());
			if (StringUtil.isNotBlank(response)) {
				Gson gson = new Gson();
				ReportInfoGson reportGson = gson.fromJson(response, ReportInfoGson.class);
				if (reportGson != null) {
					List<ReportEntity>  reports = reportGson.getReports();
					// 地图和列表用的是同一份数据，所以需要在这里设置
					setReports(reports);
				}
			}
			handler.sendEmptyMessage(filter_reports);
		} catch (Exception e) {
			isLoading = false;
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					setMapMenu();
					setSupportProgressBarIndeterminateVisibility(false);
				}
			});
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case filter_reports:
			isLoading = false;
			if (mapFragment != null) {
				mapFragment.locateTo();
			}
			if (listFragment != null) {
				listFragment.init();
			}
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case filter_reports:
			isLoading = true;
			filterReports();
			break;

		default:
			break;
		}
	}
}
